package com.test.service.impl;

import com.test.bean.FilterAndSearchData;
import com.test.bean.FilterData;
import com.test.dao.FilterAndSearchDao;
import com.test.service.IFilterAndSearchService;
import com.test.util.CreateElementUtil;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

@Service
public class FilterAndSearchServiceImpl implements IFilterAndSearchService {
    @Autowired
    FilterAndSearchDao filterAndSearchDao;

    private static Logger logger = LoggerFactory.getLogger(FilterAndSearchServiceImpl.class);

    @Override
    public Object dealFilterAndSearchData(List<FilterData> allData, FilterAndSearchData data) {
        Map returnResult = new HashMap();
        returnResult.put("success", 1);
        //生成xml的内容
        String tableName = data.getTableName();
        String orderby = data.getOrderBy();
        //获取查询列表select 语句
        StringBuilder selectMsg = new StringBuilder("select ");
        selectMsg.append("${columns}").append(" from ").append(tableName);
        if(null != allData && 0 < allData.size()) {
            selectMsg.append(" where 1 = 1 ");
        }
        //获取查询详细select语句
        StringBuilder detailMsg = new StringBuilder("select ");
        detailMsg.append("${columns} ").append("from ").append(tableName).append(" where ")
                .append(data.getPrimaryName()).append(" = #{id}");

        //创建UUID 用户生成namespace以及select的id
        String uuid = UUID.randomUUID().toString();
        data.setFid(uuid);
        try {
            // 1、生成一个根节点
            Element rss = new Element("mapper");
            // 2、为节点添加属性
            rss.setAttribute("namespace", "namespace_" + uuid);

            //2.1  生成查询列表select
            Element listSelect = new Element("select");
            listSelect.setAttribute("id", "query" + uuid);
            listSelect.setAttribute("resultType", "Map");
            listSelect.setAttribute("parameterType", "java.util.Map");
            listSelect.addContent(selectMsg.toString());
            CreateElementUtil.createChildElement(listSelect, allData);
            if(!"".equals(orderby)) {
                listSelect.addContent("ORDER BY " +  orderby);
            }
            rss.addContent(listSelect);

            //2.2  生成查询详细select
            Element detailSelect = new Element("select");
            detailSelect.setAttribute("id", "detailquery" + uuid);
            detailSelect.setAttribute("resultType", "Map");
            detailSelect.setAttribute("parameterType", "java.util.Map");
            detailSelect.addContent(detailMsg.toString());
            rss.addContent(detailSelect);

            // 3、生成一个document对象
            Document document = new Document(rss, new DocType("mapper", "-//mybatis.org//DTD Mapper 3.0//EN", "http://mybatis.org/dtd/mybatis-3-mapper.dtd"));
            Format format = Format.getCompactFormat();
            // 设置换行Tab或空格
            format.setIndent("    ");
            format.setEncoding("UTF-8");
            // 4、创建XMLOutputter的对象
            // XMLOutputter outputer = new XMLOutputter(format);
            //设置属性和内容不自动转义
            XMLOutputter outputer = new XMLOutputter(format) {
                @Override
                public String escapeElementEntities(String str) {
                    return str;
                }
                @Override
                public String escapeAttributeEntities(String str) {
                    return str;
                }
            };
            String folderStr = CreateElementUtil.fileFolder;
            File folder = new File(folderStr);
            if(!folder.exists()) {
                folder.mkdirs();
            }
            // 5、利用outputer将document转换成xml文档
            File file = new File(folderStr + "\\" + uuid + ".xml");
            if(!file.exists()) {
                file.createNewFile();
            }
            outputer.output(document, new FileOutputStream(file));
            logger.info("生成xml成功，文件路径为:" + file.getAbsolutePath());
            data.setFilePath(file.getAbsolutePath());
            data.setCreateDate(new Date());
            data.setUpdateDate(new Date());
            this.insert(data);
            returnResult.put("id", uuid);
        } catch (Exception e) {
            returnResult.put("success", 0);
            returnResult.put("errMsg", "保存信息出错");
            logger.error("生成xml失败", e);
        }
        return returnResult;
    }

    @Override
    public List getAllTableName(Map map) {
        Map param = new HashMap();
        String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = #{schema}";
        param.put("sqlStr", sql);
        param.put("schema", map.get("schema"));
        List list = filterAndSearchDao.querySql(param);
        return list;
    }

    @Override
    public Map queryTableColumns(Map map) {
        String tableName = map.get("tableName").toString();
        Map result = new HashMap();
        result.put("success",  1);
        //先判断表是否存在
        List tableList = filterAndSearchDao.queryOneTable(map);
        if(null == tableList || 0 == tableList.size()) {
            result.put("success",  0);
            result.put("errMsg", "表" + tableName + "不存在");
            return result;
        }
        List<Map> columnList = filterAndSearchDao.queryTableColumns(map);
        Map data = new HashMap();
        data.put("total", columnList.size());
        data.put("rows", columnList);
        result.put("data", data);
        return result;
    }

    @Override
    public void insert(FilterAndSearchData data) {
        filterAndSearchDao.insert(data);
    }

    @Override
    public FilterAndSearchData getFilterAndSearchById(String fid) {
        Map param = new HashMap();
        param.put("fid", fid);
        List<FilterAndSearchData> dataList = filterAndSearchDao.findFilterAndSearchData(param);
        if(null != dataList && 0 < dataList.size()) {
            return dataList.get(0);
        }
        return null;
    }

//    private String createXmlTest() {
//
//        try {
//            // 1、生成一个根节点
//            Element rss = new Element("mapper");
//            // 2、为节点添加属性
//            rss.setAttribute("namespace", "spacex");
//            Element channel = new Element("select");
//            channel.setAttribute("id", "queryx");
//            channel.setAttribute("resultType", "Map");
//            channel.setAttribute("parameterType", "java.util.Map");
//            channel.addContent("SELECT\n" +
//                    "\t\tarea_id,\n" +
//                    "\t\tarea_name,\n" +
//                    "\t\tarea_desc,\n" +
//                    "\t\tpriority,\n" +
//                    "\t\tcreate_time,\n" +
//                    "\t\tlast_edit_time\n" +
//                    "\t\tFROM\n" +
//                    "\t\ttb_area where 1 = 1");
//            Element ifElement = new Element("if");
//            ifElement.setAttribute("test", "name != null && name != ''");
//            ifElement.setText("and area_name = #{name}");
//            channel.addContent(ifElement);
//            channel.addContent("ORDER BY\n" +
//                    "\t\tpriority DESC");
//            rss.addContent(channel);
//
//            // 3、生成一个document对象
//            Document document = new Document(rss, new DocType("mapper", "-//mybatis.org//DTD Mapper 3.0//EN", "http://mybatis.org/dtd/mybatis-3-mapper.dtd"));
//            Format format = Format.getCompactFormat();
//            // 设置换行Tab或空格
//            format.setIndent("  ");
//            format.setEncoding("UTF-8");
//            XMLOutputter outputer = new XMLOutputter(format) {
//                @Override
//                public String escapeElementEntities(String str) {
//                    return str;
//                }
//                @Override
//                public String escapeAttributeEntities(String str) {
//                    return str;
//                }
//            };
//
//            // 4、创建XMLOutputter的对象
//            // XMLOutputter outputer = new XMLOutputter(format);
//
//            // 5、利用outputer将document转换成xml文档
//            File file = new File("D:\\aa_bulesky\\rssNew.xml");
//            if(!file.exists()) {
//                file.createNewFile();
//            }
//            outputer.output(document, new FileOutputStream(file));
//
//            System.out.println("生成rssNew.xml成功");
//        } catch (Exception e) {
//            System.out.println("生成rssNew.xml失败");
//            e.printStackTrace();
//        }
//        return null;
//    }
}
